//
//  SelectDetailViewController.m
//  礼物go
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SelectDetailViewController.h"
#import "SelectDetailModel.h"
#import "LoginViewController.h"
#import <MBProgressHUD.h>

//图片高度
#define PIC_HEIGHT SCREENWIDTH * 329 / 720.0


@interface SelectDetailViewController ()<UIWebViewDelegate,UIScrollViewDelegate, UMSocialUIDelegate>

@property(nonatomic,strong)UIWebView *presentWebView;
@property(nonatomic,strong)UIScrollView *contentScrollView;
@property (nonatomic, strong)UIImageView *headerImageV;
@property (nonatomic, strong)UILabel *descripeLabel;
@property (nonatomic, strong) UIView *imgalphaView; // 顶部图片的灰色蒙版

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *shareView;
@property (nonatomic, strong) UIButton *likeButton;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) UIButton *commentButton;

@property(nonatomic,strong)SelectDetailModel *SDModel;


@end

@implementation SelectDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 支持右滑返回
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"攻略详情";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:  UIBarButtonSystemItemReply target:self action:@selector(leftButtonAction)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
   // [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    [self scrollViewDidScroll:self.contentScrollView];
    
    [self getData];
    [self setUpView];
   // [self.view setAutoresizesSubviews:NO];
    
//    self.tabView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHeight - 49, SCREENWIDTH, 49)];
//    [self.view addSubview:self.tabView];
    
    
    
    // Do any additional setup after loading the view.
}

-(void)setUpView{
    //添加子视图并重写getter方法
    [self.view addSubview:self.contentScrollView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.shareView];

}

-(void)getData{
    
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/posts/%@",self.dataId];
    [LYNetworking ly_GetWithURL:urlStr Parameter:nil success:^(id result) {
        NSDictionary *dataDic = [result objectForKey:@"data"];
        self.SDModel = [[SelectDetailModel alloc] init];
        [self.SDModel setValuesForKeysWithDictionary:dataDic];
        
     //赋值
        [self.headerImageV sd_setImageWithURL:[NSURL URLWithString:_SDModel.cover_image_url] placeholderImage:[UIImage imageNamed:@"picholder"]];
    //加载网页的字符串
        
    self.presentWebView.frame = CGRectMake(0, CGRectGetMaxY(self.headerImageV.frame), SCREENWIDTH, 0.2);
        self.presentWebView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFAFA,0xBEBEBE);
        
        [self.presentWebView loadHTMLString:self.SDModel.content_html baseURL:nil];
        self.descripeLabel.text = self.SDModel.title;
       
   //设置底部按钮

        [self.likeButton setTitle:[self.SDModel.likes_count stringValue] forState:UIControlStateNormal];
        NSInteger num = [self.SDModel.likes_count integerValue] + 1;
        [self.likeButton setTitle:[NSString stringWithFormat:@"%ld",num] forState:UIControlStateSelected];
        
    [self.shareButton setTitle:[self.SDModel.shares_count stringValue] forState:UIControlStateNormal];
        
        [self.commentButton setTitle:[self.SDModel.comments_count stringValue] forState:UIControlStateNormal];
        
        
//        //创建webView
//        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHeight - 49)];
//        [webView setUserInteractionEnabled:YES];
//        [webView setScalesPageToFit:YES];
//        [self.view addSubview:webView];
//        
//        //加载网页
//        // NSLog(@"%@",self.urlString);
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.SDModel.url]];
//        [webView loadRequest:request];
        
        
    } error:^(NSError *error) {
        
        
    }];
}

//重写scrollView的getter方法
-(UIScrollView *)contentScrollView{
    if (!_contentScrollView) {
        self.contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHeight - 49)];
        _contentScrollView.backgroundColor = [UIColor whiteColor];
        _contentScrollView.delegate = self;
        //添加imageView
        [_contentScrollView addSubview:self.headerImageV];
        
         [_contentScrollView addSubview:self.imgalphaView];
        //添加webView
        [_contentScrollView addSubview:self.presentWebView];
        
        [_contentScrollView addSubview:self.descripeLabel];
        
    }
    return _contentScrollView;
}

//重写ImageView的getter方法
-(UIImageView *)headerImageV{
    if (_headerImageV == nil) {
        self.headerImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, PIC_HEIGHT * 1.4)];
       //设置imageView高度改变时宽度也跟着改变
       self.headerImageV.contentMode =  UIViewContentModeScaleAspectFill;
    }
    return _headerImageV;
}

- (UIView *)imgalphaView {
    
    if (!_imgalphaView) {
        self.imgalphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, CGRectGetMaxY(self.headerImageV.frame))];
        self.imgalphaView.backgroundColor = [UIColor blackColor];
        self.imgalphaView.alpha = 0.3;
    }
    return _imgalphaView;
}



//webView
-(UIWebView *)presentWebView{
    if (_presentWebView == nil) {
        //SCREEN_HEIGHT - CGRectGetMaxY(self.imageView.frame)
        
        self.presentWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerImageV.frame), SCREENWIDTH, 0.2)];
        _presentWebView.delegate = self;
        _presentWebView.backgroundColor = [UIColor whiteColor];
        _presentWebView.scrollView.scrollEnabled = NO;
    }
    return _presentWebView;
}

//descripeLabel
-(UILabel *)descripeLabel{
    if (!_descripeLabel) {
        self.descripeLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.headerImageV.frame) - 64, SCREENWIDTH - 30, 54)];
        _descripeLabel.numberOfLines = 0;
        _descripeLabel.textColor = [UIColor whiteColor];
        _descripeLabel.font = [UIFont boldSystemFontOfSize:20];
    }
    return _descripeLabel;
}


//(需调整)bottomView
- (UIView *)bottomView {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userName = [user objectForKey:@"userName"];
    
    if (_bottomView == nil) {
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHeight - 49 - 64, SCREENWIDTH, 49)];
        _bottomView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFAFA,0xBEBEBE);
        
        self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.likeButton.frame = CGRectMake(0, 0, SCREENWIDTH / 3.0 - 0, 49);
        self.likeButton.titleLabel.font = [UIFont systemFontOfSize:15];
        //self.likeButton.adjustsImageWhenHighlighted = NO;
        [self.likeButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.likeButton.titleLabel.textColor = [UIColor lightGrayColor];
        [self.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:self.likeButton];
       // [self.likeButton setImage:[UIImage imageNamed:@"content-details_like_16x16_@2x"] forState:UIControlStateNormal];
        
        self.likeButton.selected = [[DataFMDBHandle shareDataFMDBHandle] presentDataWithId:self.dataId WithAccount:userName];
        
        [self.likeButton setImage:[UIImage imageNamed:@"content-details_like_16x16_@2x"] forState:UIControlStateNormal];
        
        [self.likeButton setImage:[UIImage imageNamed:@"content-details_like_selected_16x16_@2x"] forState:UIControlStateSelected];

        
        
        
        
        self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //self.shareButton.backgroundColor = [UIColor blueColor];
        self.shareButton.frame = CGRectMake(SCREENWIDTH / 3.0, 0, SCREENWIDTH / 3.0, 49);
        self.shareButton.titleLabel.font = [UIFont systemFontOfSize:15];
        self.shareButton.adjustsImageWhenHighlighted = NO;
        [self.shareButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        //[self.shareButton setImage:[UIImage imageNamed:@"fenxiang.png"] forState:UIControlStateNormal];
        [self.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:self.shareButton];
        [self.shareButton setImage:[UIImage imageNamed:@"content-details_share_16x16_@2x"] forState:UIControlStateNormal];
        
        
        self.commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //self.commentButton.backgroundColor = [UIColor redColor];
        self.commentButton.frame = CGRectMake(SCREENWIDTH / 3.0 * 2, 0, SCREENWIDTH / 3.0, 49);
        self.commentButton.titleLabel.font = [UIFont systemFontOfSize:15];
        self.commentButton.adjustsImageWhenHighlighted = NO;
        [self.commentButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        //[self.commentButton setImage:[UIImage imageNamed:@"pinglun.png"] forState:UIControlStateNormal];
        [self.commentButton addTarget:self action:@selector(commentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:self.commentButton];
         [self.commentButton setImage:[UIImage imageNamed:@"content-details_comments_16x16_@2x"] forState:UIControlStateNormal];
        
        
    }
    
    return _bottomView;
}

//喜欢按钮
-(void)likeButtonAction:(UIButton *)button{
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    keyAnimation.values = @[@(0.5),@(1.0),@(1.5)];
    keyAnimation.duration = 0.3;
    [self.likeButton.layer addAnimation:keyAnimation forKey:@"buttonkey"];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userName = [user objectForKey:@"userName"];
    NSString *string = [user objectForKey:@"status"];
   // NSLog(@"%@",string);
    if (![string isEqualToString:@"yes"]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:^{
            
            
        }];
        
    }else if ([[DataFMDBHandle shareDataFMDBHandle] presentDataWithId:self.dataId WithAccount:userName]){
        [[DataFMDBHandle shareDataFMDBHandle] deletePresent:userName MyId:self.dataId];
        
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"取消喜欢";
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(2);
            
        } completionBlock:^{
            [hud removeFromSuperview];
            
        }];
        
        button.selected = !button.selected;
    }else{
        [[DataFMDBHandle shareDataFMDBHandle] insertPresent:self.SDModel WithAccount:userName];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"喜欢成功";
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(2);
            
        } completionBlock:^{
            [hud removeFromSuperview];
            
        }];
        
        button.selected = !button.selected;
        
    }
    

}

//分享按钮
-(void)shareButtonAction:(UIButton *)button{
    
    //分享第二步
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"558936d367e58eb81b001298"
                                      shareText:@"欢迎使用礼物GO"
                                     shareImage:[UIImage imageNamed:@"box_01"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToDouban,nil]
                                       delegate:self];
}

//评论按钮
-(void)commentButtonAction:(UIButton *)button{
    
}



//webView代理方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}

//webView结束加载
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //document.documentElement.scrollHeight为页面的滚动高度
    //获取网页内容高度
    float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];
    //设置webview的坐标
    self.presentWebView.frame = CGRectMake(0, CGRectGetMaxY(self.headerImageV.frame), SCREENWIDTH,height );
    
    self.contentScrollView.contentSize = CGSizeMake(SCREENWIDTH, self.headerImageV.frame.size.height + height - 70);
    
}


//设置滑动效果(ImageView的效果)
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat yOffset  = scrollView.contentOffset.y;
    
    CGRect frame = self.headerImageV.frame;
    
    frame.origin.y = yOffset;
    frame.size.height = -yOffset + PIC_HEIGHT * 1.4;
   
//    frame.origin.x = -(frame.size.height*SCREENWIDTH/(PIC_HEIGHT * 1.4) -  SCREENWIDTH)/2;
//    frame.size.width = frame.size.height*SCREENWIDTH/(PIC_HEIGHT * 1.4);
    
    self.headerImageV.frame = frame;
    
    self.imgalphaView.frame = CGRectMake(0,frame.origin.y, SCREENWIDTH, CGRectGetMaxY(self.headerImageV.frame) - frame.origin.y);
    
    self.descripeLabel.frame = CGRectMake(15, CGRectGetMaxY(self.headerImageV.frame) - 64, SCREENWIDTH - 30, 54);
}


-(void)leftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
